package it.giuseppetrisciuoglio.lyrics.service.twittersearch;

import it.giuseppetrisciuoglio.lyrics.http.HttpReader;
import it.giuseppetrisciuoglio.lyrics.service.AbstractJsonService;
import it.giuseppetrisciuoglio.lyrics.service.twittersearch.model.SearchResponse;
import it.giuseppetrisciuoglio.lyrics.service.twittersearch.model.Response;
import it.giuseppetrisciuoglio.lyrics.utils.StringUtilies;

import java.io.IOException;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class TwitterService extends AbstractJsonService<SearchResponse>{
	
	private final int RATE_LIMIT = 180;

	private final String ENDPOINT_URL = "http://search.twitter.com/search.json?q=";
	
	private int countRateLimit = 0;
	
	@Autowired
	private HttpReader httpReader;
	
	@Value("${http.defaultCharset}")
	private String defaultCharset;
	
	private final transient Logger log = LoggerFactory.getLogger(getClass());
	
	public String findYoutubeVideoByArtistaAndTitolo(String artista, String titolo){
		log.debug("findYoutubeVideoByArtistaAndTitolo(): artista={}, titolo={}", artista, titolo);
		String result = null;
		try {
			String url = ENDPOINT_URL.concat(URLEncoder.encode(artista.concat(" ").concat(titolo), defaultCharset));
			log.debug("findYoutubeVideoByArtistaAndTitolo(): url={}", url);
			if (countRateLimit <= RATE_LIMIT){
				String responseTxt = httpReader.getResponse(url);
				SearchResponse searchResponse = parseJson(responseTxt, SearchResponse.class);
				for (Response response : searchResponse.getResults()) {
					if (response.getText() != null && response.getText().indexOf("youtube") > 0){
						log.debug("findYoutubeVideoByArtistaAndTitolo(): response={}", response.getText());
						result = StringUtilies.getTwitterURL(response.getText());
					}
				}
			}else{
				// TODO send asyncMessage :-)
			}
			countRateLimit++;
		} catch (IOException e) {
			log.error("findYoutubeVideoByArtistaAndTitolo(): exception={}", e.getMessage());
			throw new RuntimeException(e);
		}
		return result;
	}
	
	public void resetCountRateLimit(){
		countRateLimit = 0;
	}
	

}